package com.wwz.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwz.feign.FileClients;
import com.wwz.mapper.UserMapper;
import com.wwz.pojo.FileInfo;
import com.wwz.pojo.Personnel;
import com.wwz.pojo.User;
import com.wwz.pojo.model.LoginModel;
import com.wwz.pojo.query.UserQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户接口实现
 * @date 2022/04/08 28:08:24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private FileClients fileClients;

    @Override
    public LoginModel login(LoginModel loginModel) {
        String userName = loginModel.getUserName();
        String password = loginModel.getPassWord();

        Boolean rememberMe = loginModel.getRememberMe();
        if (rememberMe == null){
            rememberMe = false;
        }

        User user = getOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUserName, userName)
                        .eq(User::getPassWord, password)
                , false);

        if (user == null || user.getStatus()==0){
            return null;
        }

        StpUtil.login(user.getId(),rememberMe);

        loginModel.setUser(user);
        loginModel.setSatoken(StpUtil.getTokenValue());

        return loginModel;
    }

    @Override
    public IPage<User> toPage(UserQuery query) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(query.getUserName())){
            wrapper.like(User::getUserName,query.getUserName());
        }
        wrapper.orderByDesc(User::getCreateTime);

        IPage<User> page = this.page(query.toPage(), wrapper);

        // 文件info填充
        List<FileInfo> result = fileClients.fileList().getResult();
        Map<String, List<FileInfo>> fileMap = result.stream().collect(Collectors.groupingBy(FileInfo::getDataId));
        for (User user : page.getRecords()) {
            List<FileInfo> fileInfos = fileMap.get(user.getPhoto());
            if (CollUtil.isNotEmpty(fileInfos)){
                user.setFileInfo(fileInfos.get(0));
            }
        }
        return page;
    }

    @Override
    public void addOrUpdate(User user) {
        User one = this.getById(user);

        if (one == null){
            user.setId(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setStatus(1);
            save(user);
        }
        updateById(user);
    }
}
